<template>
  <Scrollbar ref="scrollbar">
    <div class="flex-row no-select nav-bar-container" ref="nav-bar-container">
      <div :key="`nav-bar-item-${i}`"
           :class="['item',__index===i?'active':'']"
           :style="itemStyles"
           @click="e=>onChange(i,item,e)" v-for="(item,i) of bars">
        {{ item.label }}
      </div>
      <div class="bar" :style="barStyles"></div>
    </div>
  </Scrollbar>
</template>

<script lang="ts">
import {defineComponent, nextTick, PropType} from "vue";
import {isEmpty} from "@/utils/helpers";
import Scrollbar from "@/components/scrollbar/Scrollbar.vue";

export default defineComponent({
  name: "CNavBar",
  components: {
    Scrollbar
  },
  emits: [
    'onChange'
  ],
  props: {
    bars: {
      required: true,
      type: Array as PropType<any[]>,
      default: () => []
    },
    barPadding: {
      type: Number,
      default: 10,
    },
    index: Number,
    itemStyles: {
      type: Object,
      default: () => {
        return {}
      }
    }
  },
  data() {
    return {
      __index: -1,
      barStyles: {}
    }
  },
  watch: {
    bars: {
      immediate: true,
      handler(val: any[]) {
        if (this.__index === -1 && val.length > 0) {
          this.__index = this.index || 0;
        }
      },
    },
    __index(val: number) {
      nextTick(() => {
        this.refreshBarStyles(val)
      })
    }
  },
  methods: {
    refreshBarStyles(index: number) {
      const barPadding: number = this.barPadding || 0;
      const refs: HTMLElement = this.$refs['nav-bar-container'] as HTMLElement;
      let styles = {}
      if (refs instanceof HTMLElement) {
        const el: HTMLElement = refs.children[index] as HTMLElement;
        if (!isEmpty(el)) {
          styles = {
            left: `${el.offsetLeft + barPadding}px`,
            width: `${el.offsetWidth - 2 * barPadding}px`,
          }
        }
      }
      this.barStyles = styles;
    },
    onChange(index: number, item: any, e: MouseEvent) {
      const el = this.$refs['scrollbar'] as any
      el.onTryScroll(e.pageX)
      this.__index = index
      this.$emit('onChange', {item, index});
    }
  }
})
</script>

<style lang="less" scoped>
.nav-bar-container {
  position: relative;

  .item {
    padding: 0 10px;
    line-height: 50px;
    font-size: 16px;
    flex-shrink: 0;

    &.active {
      //color: @primaryColor;
      color: #F9574F;
    }
  }

  .bar {
    //background-color: @primaryColor;
    background-color: #F9574F;
    width: 0;
    height: 5px;
    border-radius: 10px;
    position: absolute;
    bottom: 0;
    transition: all 100ms;
  }
}
</style>